package com.wentao.thisService.service.impl;

import com.wentao.thisFacade.common.enums.ExceptionCode;
import com.wentao.thisFacade.common.enums.business.PartnerTypeCode;
import com.wentao.thisFacade.common.enums.business.RoleCodeEnum;
import com.wentao.thisFacade.common.enums.business.UserLockStatusEnum;
import com.wentao.thisFacade.common.enums.business.ValidStatusEnum;
import com.wentao.thisFacade.common.exception.CustomException;
import com.wentao.thisFacade.domain.PageBase;
import com.wentao.thisFacade.domain.reqeust.PartnerRequest;
import com.wentao.thisFacade.domain.reqeust.PerformanceListRequest;
import com.wentao.thisFacade.domain.result.PartnerPageResult;
import com.wentao.thisFacade.domain.result.PartnerResult;
import com.wentao.thisFacade.domain.result.PerformanceVal;
import com.wentao.thisService.common.CommonFunction;
import com.wentao.thisService.mapper.CommonDao;
import com.wentao.thisService.mapper.PartnerDao;
import com.wentao.thisService.mapper.UserAuthorityDao;
import com.wentao.thisService.mapper.UserDao;
import com.wentao.thisService.model.PartnerEntity;
import com.wentao.thisService.model.UserAuthorityEntity;
import com.wentao.thisService.model.UserEntity;
import com.wentao.thisService.model.entities.IntResultEntity;
import com.wentao.thisService.model.entities.PageEntity;
import com.wentao.thisService.service.PartnerService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Auther: ZhaiYanTao
 * @Date: 2020/3/28 15:07
 * @Description: 合伙人/业务员service实现
 */
@Service
public class PartnerServiceImpl implements PartnerService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private UserAuthorityDao userAuthorityDao;

    @Autowired
    private PartnerDao partnerDao;

    @Autowired
    private CommonDao commonDao;

    /**
     * @see PartnerService#pagePartner(PartnerRequest)
     */
    @Override
    public PartnerPageResult pagePartner(PartnerRequest partnerRequest) {
        PartnerEntity searchPartner = new PartnerEntity();
        searchPartner.setName(partnerRequest.getName());
        searchPartner.setIdentity(partnerRequest.getIdentity());
        searchPartner.setTel(partnerRequest.getTel());
        searchPartner.setProvinceCode(partnerRequest.getProvinceCode());
        searchPartner.setCityCode(partnerRequest.getCityCode());
        searchPartner.setDistrictCode(partnerRequest.getDistrictCode());
        searchPartner.setStatus(ValidStatusEnum.VALID.getCode());
        PageEntity pageEntity = getPageEntity(partnerRequest.getPageEntity());

        // 用户信息
        UserEntity searchUser = new UserEntity();
        searchUser.setStatus("Y");
        List<UserEntity> userEntityList = userDao.Search(searchUser);
        Map<Long, UserEntity> userIdEntityMap = new HashMap<>();
        for (UserEntity userEntity : userEntityList) {
            userIdEntityMap.put(userEntity.getId(), userEntity);
        }

        // 合伙人分页数据
        List<PartnerEntity> partnerEntityList = partnerDao.SearchPage(searchPartner, pageEntity);
        // 总行数
        IntResultEntity count = partnerDao.Count(searchPartner);

        List<PartnerResult> partnerResultList = new ArrayList<>();
        PartnerResult partnerResult;
        if (null != partnerEntityList && partnerEntityList.size() > 0) {
            for (PartnerEntity partnerEntity : partnerEntityList) {
                String lockStatus = userIdEntityMap.get(partnerEntity.getUserId()).getLockStatus();
                partnerResult = transform(partnerEntity, lockStatus);
                if (null != partnerResult) {
                    partnerResultList.add(partnerResult);
                }
            }
        }

        PartnerPageResult partnerPageResult = new PartnerPageResult();
        partnerPageResult.setRowCount(count.getResult());
        partnerPageResult.setPartnerList(partnerResultList);

        return partnerPageResult;
    }

    /**
     * @see PartnerService#listParentPartnerByLocation(PartnerRequest)
     */
    @Override
    public List<PartnerResult> listParentPartnerByLocation(PartnerRequest partnerRequest) {
        PartnerEntity searchPartner = new PartnerEntity();
        searchPartner.setProvinceCode(partnerRequest.getProvinceCode());
        searchPartner.setCityCode(partnerRequest.getCityCode());
        searchPartner.setDistrictCode(partnerRequest.getDistrictCode());
        searchPartner.setPartnerType(PartnerTypeCode.PARTNER.getCode());
        searchPartner.setStatus(ValidStatusEnum.VALID.getCode());

        // 用户信息
        UserEntity searchUser = new UserEntity();
        searchUser.setStatus(ValidStatusEnum.VALID.getCode());
        List<UserEntity> userEntityList = userDao.Search(searchUser);
        Map<Long, UserEntity> userIdEntityMap = new HashMap<>();
        for (UserEntity userEntity : userEntityList) {
            userIdEntityMap.put(userEntity.getId(), userEntity);
        }

        // 合伙人信息
        List<PartnerEntity> partnerEntityList = partnerDao.Search(searchPartner);

        List<PartnerResult> partnerResultList = new ArrayList<>();
        PartnerResult partnerResult;
        if (null != partnerEntityList && partnerEntityList.size() > 0) {
            for (PartnerEntity partnerEntity : partnerEntityList) {
                if (null != partnerEntity && null != userIdEntityMap.get(partnerEntity.getUserId()) && "Y".equals(userIdEntityMap.get(partnerEntity.getUserId()).getLockStatus())) {
                    partnerResult = transform(partnerEntity, "Y");
                    if (null != partnerResult) {
                        partnerResultList.add(partnerResult);
                    }
                }
            }
        }

        return partnerResultList;
    }

    /**
     * @see PartnerService#savePartner(PartnerRequest)
     */
    @Override
    public Boolean savePartner(PartnerRequest partnerRequest) {
        Timestamp nowTimestamp = commonDao.getNowTime();
        String nowTimeString = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(nowTimestamp);
        String uuidStr = CommonFunction.CreateUUIDString();
        String password = CommonFunction.CreateMd5("888888");
        String inviteCode = CommonFunction.CreateUUIDString().substring(1, 7);

        // 保存用户
        UserEntity saveUser = new UserEntity();
        saveUser.setUserName(partnerRequest.getName());
        saveUser.setUserCode(uuidStr);
        saveUser.setPassword(password);
        saveUser.setMobile(partnerRequest.getTel());
        saveUser.setLockStatus(UserLockStatusEnum.UN_LOCK.getCode());
        saveUser.setUserSource(partnerRequest.getParentPartnerId());
        saveUser.setStatus(ValidStatusEnum.VALID.getCode());
        saveUser.setOwnId(partnerRequest.getParentPartnerId());
        saveUser.setCreateBy(String.valueOf(partnerRequest.getParentPartnerId()));
        saveUser.setCreateTime(nowTimeString);
        userDao.Insert(saveUser);

        // 保存用户角色
        UserAuthorityEntity saveUserAuthority = new UserAuthorityEntity();
        saveUserAuthority.setUserCode(saveUser.getUserCode());
        saveUserAuthority.setRoleCode(RoleCodeEnum.PARTNER_SALESMAN.getCode());
        saveUserAuthority.setStatus("Y");
        saveUserAuthority.setOwnId(partnerRequest.getParentPartnerId());
        saveUserAuthority.setCreateBy(String.valueOf(partnerRequest.getParentPartnerId()));
        saveUserAuthority.setCreateTime(nowTimeString);
        userAuthorityDao.Insert(saveUserAuthority);

        // 保存合伙人
        PartnerEntity savePartner = new PartnerEntity();
        savePartner.setUserId(saveUser.getId());
        savePartner.setName(partnerRequest.getName());
        savePartner.setPartnerType(partnerRequest.getPartnerType());
        savePartner.setPosition(partnerRequest.getPosition());
        savePartner.setInviteCode(inviteCode);
        savePartner.setIdentity(partnerRequest.getIdentity());
        savePartner.setTel(partnerRequest.getTel());
        savePartner.setDivide(partnerRequest.getDivide());
        savePartner.setStatus(ValidStatusEnum.VALID.getCode());
        savePartner.setOwnId(partnerRequest.getParentPartnerId());
        savePartner.setCreateBy(String.valueOf(partnerRequest.getParentPartnerId()));
        savePartner.setCreateTime(nowTimeString);
        savePartner.setProvinceCode(partnerRequest.getProvinceCode());
        savePartner.setProvinceName(partnerRequest.getProvinceName());
        savePartner.setCityCode(partnerRequest.getCityCode());
        savePartner.setCityName(partnerRequest.getCityName());
        savePartner.setDistrictCode(partnerRequest.getDistrictCode());
        savePartner.setDistrictName(partnerRequest.getDistrictName());
        savePartner.setParentPartnerId(partnerRequest.getParentPartnerId());
        partnerDao.Insert(savePartner);

        // TODO: 2020/3/28 邀请码加入缓存，校验也可从redis获取再校验
//        redisExecutor.addSet(ConstString.INVIT_ECODE, inviteCode);

        return true;
    }

    /**
     * @see PartnerService#updatePartner(PartnerRequest)
     */
    @Override
    public Boolean updatePartner(PartnerRequest partnerRequest) {
        Timestamp nowTimestamp = commonDao.getNowTime();
        String nowTimeString = CommonFunction.GetDateByTime(nowTimestamp.getTime());
//        String nowTimeString = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(nowTimestamp);

        // 合伙人信息
        PartnerEntity searchPartner = new PartnerEntity();
        searchPartner.setId(partnerRequest.getId());
        List<PartnerEntity> partnerEntityList = partnerDao.Search(searchPartner);
        if (null == partnerEntityList || partnerEntityList.size() == 0) {
            throw new CustomException(ExceptionCode.PARTNER_NOT_EXIST);
        }
        PartnerEntity partnerEntity = partnerEntityList.get(0);

        // 用户信息
        UserEntity searchUser = new UserEntity();
        searchUser.setId(partnerEntity.getUserId());
        List<UserEntity> userEntityList = userDao.Search(searchUser);
        if (null == userEntityList || userEntityList.size() == 0) {
            throw new CustomException(ExceptionCode.USER_NOT_EXIST);
        }
        UserEntity userEntity = userEntityList.get(0);

        // 保存用户
        if (StringUtils.isNotBlank(partnerRequest.getName())) {
            userEntity.setUserName(partnerRequest.getName());
        }
        if (StringUtils.isNotBlank(partnerRequest.getTel())) {
            userEntity.setMobile(partnerRequest.getTel());
        }
        if (StringUtils.isNotBlank(partnerRequest.getLockStatus())) {
            userEntity.setLockStatus(partnerRequest.getLockStatus());
        }
        if (null != partnerRequest.getParentPartnerId()) {
            userEntity.setUserSource(partnerRequest.getParentPartnerId());
            userEntity.setOwnId(partnerRequest.getParentPartnerId());
        }
        // TODO: 2020/3/28 延伸到所有，creatby 或者 modifyby 应该存操作人的id（系统登录账号）
        userEntity.setModifyBy(String.valueOf(partnerRequest.getParentPartnerId()));
        userEntity.setModifyTime(nowTimeString);
        userDao.UpdateById(userEntity);

        // 保存合伙人
        if (StringUtils.isNotBlank(partnerRequest.getName())) {
            partnerEntity.setName(partnerRequest.getName());
        }
        if (StringUtils.isNotBlank(partnerRequest.getPartnerType())) {
            partnerEntity.setPartnerType(partnerRequest.getPartnerType());
        }
        if (StringUtils.isNotBlank(partnerRequest.getPosition())) {
            partnerEntity.setPosition(partnerRequest.getPosition());
        }
        if (StringUtils.isNotBlank(partnerRequest.getIdentity())) {
            partnerEntity.setIdentity(partnerRequest.getIdentity());
        }
        if (StringUtils.isNotBlank(partnerRequest.getTel())) {
            partnerEntity.setTel(partnerRequest.getTel());
        }
        if (null != partnerRequest.getDivide()) {
            partnerEntity.setDivide(partnerRequest.getDivide());
        }
        if (null != partnerRequest.getParentPartnerId()) {
            partnerEntity.setOwnId(partnerRequest.getParentPartnerId());
        }
        if (StringUtils.isNotBlank(partnerRequest.getProvinceCode())) {
            partnerEntity.setProvinceCode(partnerRequest.getProvinceCode());
        }
        if (StringUtils.isNotBlank(partnerRequest.getProvinceName())) {
            partnerEntity.setProvinceName(partnerRequest.getProvinceName());
        }
        if (StringUtils.isNotBlank(partnerRequest.getCityCode())) {
            partnerEntity.setCityCode(partnerRequest.getCityCode());
        }
        if (StringUtils.isNotBlank(partnerRequest.getCityName())) {
            partnerEntity.setCityName(partnerRequest.getCityName());
        }
        if (StringUtils.isNotBlank(partnerRequest.getDistrictCode())) {
            partnerEntity.setDistrictCode(partnerRequest.getDistrictCode());
        }
        if (StringUtils.isNotBlank(partnerRequest.getDistrictName())) {
            partnerEntity.setDistrictName(partnerRequest.getDistrictName());
        }
        if (null != partnerRequest.getParentPartnerId()) {
            partnerEntity.setParentPartnerId(partnerRequest.getParentPartnerId());
        }
        partnerEntity.setModifyBy(String.valueOf(partnerRequest.getParentPartnerId()));
        partnerEntity.setModifyTime(nowTimeString);
        partnerDao.UpdateById(partnerEntity);

        return true;
    }

    /**
     * @see PartnerService#deletePartner(PartnerRequest)
     */
    @Override
    public Boolean deletePartner(PartnerRequest partnerRequest) {
        Timestamp nowTimestamp = commonDao.getNowTime();
        String nowTimeString = CommonFunction.GetDateByTime(nowTimestamp.getTime());
//        String nowTimeString = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(nowTimestamp);

        // 合伙人信息
        PartnerEntity searchPartner = new PartnerEntity();
        searchPartner.setId(partnerRequest.getId());
        List<PartnerEntity> partnerEntityList = partnerDao.Search(searchPartner);
        if (null == partnerEntityList || partnerEntityList.size() == 0) {
            throw new CustomException(ExceptionCode.PARTNER_NOT_EXIST);
        }
        PartnerEntity partnerEntity = partnerEntityList.get(0);

        // 用户信息
        UserEntity searchUser = new UserEntity();
        searchUser.setId(partnerEntity.getUserId());
        List<UserEntity> userEntityList = userDao.Search(searchUser);
        if (null == userEntityList || userEntityList.size() == 0) {
            throw new CustomException(ExceptionCode.USER_NOT_EXIST);
        }
        UserEntity userEntity = userEntityList.get(0);

        // 保存用户
        userEntity.setModifyBy(String.valueOf(partnerRequest.getParentPartnerId()));
        userEntity.setModifyTime(nowTimeString);
        userEntity.setStatus(ValidStatusEnum.INVALID.getCode());
        userDao.UpdateById(userEntity);

        // 保存合伙人
        partnerEntity.setModifyBy(String.valueOf(partnerRequest.getParentPartnerId()));
        partnerEntity.setModifyTime(nowTimeString);
        partnerEntity.setStatus(ValidStatusEnum.INVALID.getCode());
        partnerDao.UpdateById(partnerEntity);

        return true;
    }

    /**
     * @see PartnerService#performanceList(PerformanceListRequest)
     */
    @Override
    public PerformanceVal performanceList(PerformanceListRequest performanceListRequest) {
//        BaseEntity<CompanyInfoPageEntity> baseEntity = CommonFunction.ConvertBaseEntity(entity, CompanyInfoPageEntity.class);
//        baseEntity.getBody().getPageEntity().setPageIndex(entity.getBody().getPageEntity().getPageIndex());
//        List<CompanyInfoEntity> companyInfoEntities = companyInfoInterface.SearchPage(baseEntity);
//        List<PerformanceListResult> results = ConvertEntity.copyEntityArray(companyInfoEntities, CompanyInfoEntity.class);
//        BaseEntity<CompanyInfoEntity> count = CommonFunction.ConvertBaseEntity(entity, CompanyInfoEntity.class);
//        IntResultEntity countVal = companyInfoInterface.Count(count);
//        val.setRowCount(countVal.getResult());
//        val.setPerformanceListResult(results);
        PerformanceVal val = new PerformanceVal();
        val.setRowCount(0);
        // TODO: 2020/3/28 业绩管理接口待处理
        return val;
    }

    /**
     * 转换方法
     *
     * @param source 合伙人地址信息PO
     * @return 合伙人地址信息VO
     */
    private PartnerResult transform(PartnerEntity source, String lockStatus) {
        if (null != source) {
            PartnerResult target = new PartnerResult();

            target.setId(source.getId());
            target.setName(source.getName());
            target.setPartnerType(source.getPartnerType());
            target.setInviteCode(source.getInviteCode());
            target.setIdentity(source.getIdentity());
            target.setTel(source.getTel());
            target.setDivide(source.getDivide());
            target.setApproveStatus(source.getApproveStatus());
            target.setStatus(source.getStatus());
            target.setOwnId(source.getOwnId());
            target.setCreateTime(source.getCreateTime());
            target.setCreateBy(source.getCreateBy());
            target.setModifyTime(source.getModifyTime());
            target.setModifyBy(source.getModifyBy());
            target.setApproveStep(source.getApproveStep());
            target.setPosition(source.getPosition());
            target.setLockStatus(lockStatus);
            target.setUserId(source.getUserId());
            target.setProvinceCode(source.getProvinceCode());
            target.setProvinceName(source.getProvinceName());
            target.setCityCode(source.getCityCode());
            target.setCityName(source.getCityName());
            target.setDistrictCode(source.getDistrictCode());
            target.setDistrictName(source.getDistrictName());
            target.setParentPartnerId(source.getParentPartnerId());

            return target;
        }
        return null;
    }

    /**
     * 获取分页entity
     *
     * @param pageBase 分页信息
     * @return 分页entity
     */
    PageEntity getPageEntity(PageBase pageBase) {
        PageEntity pageEntity = new PageEntity();
        pageEntity.setPageIndex(pageBase.getPageIndex());
        pageEntity.setPageSize(pageBase.getPageSize());
        pageEntity.setOrderString(pageBase.getOrderString());
        pageEntity.setOrderType(pageBase.getOrderType());
        return pageEntity;
    }
}
